package com.study.locks.redis;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

/**
 * 大宝剑续钟功能
 * 它应该有一个监听线程。。。
 *
 * @author: chenhs
 * @date: Created in 11:19 2019/12/16
 **/
public class SellTicket_Redisson implements Runnable {

    //100张票
    private int tickets = 100;

    private RLock lock = getRedissonLock();

    private RLock getRedissonLock() {
        Config config = new Config();
        SingleServerConfig singleConfig = config.useSingleServer();
        singleConfig.setAddress("redis://localhost:6379");
        // 如果有密码
        singleConfig.setPassword("abc123");

        Redisson redisson = (Redisson) Redisson.create(config);

        //获得锁对象实例
        RLock lock = redisson.getLock("dabaojian");
        return lock;
    }


    @Override
    public void run() {
        while (tickets > 0) {

            //开启锁
            lock.lock();
            //lock.tryLock();
            try {
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //窗口号
                    System.out.println(Thread.currentThread().getName() + "正在出票第 " + (tickets--) + " 张票");
                }
            } finally {
                lock.unlock();
            }
        }
    }

}
